<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="申请单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="purchase_requisition" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="申请人员" prop="name">
          <el-input v-model="formData.applicationName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="申请日期" prop="purchaseTime">
          <el-date-picker
            v-model="formData.applicationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="采购类型" prop="purchaseTypeCode">
          <DictSelect
            :band-value.sync="formData.purchaseTypeCode"
            dict-type="purchaseTypeCode"
          />
        </el-form-item>
        <!--        <el-form-item label="计划单号" class="clickChoose">-->
        <!--          <el-select-->
        <!--            v-model="formData.belongBysStr"-->
        <!--            multiple-->
        <!--            clearable-->
        <!--            filterable-->
        <!--            placeholder="请选择"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in equipmentList"-->
        <!--              :key="item.id"-->
        <!--              :label="item.deviceName"-->
        <!--              :value="item.id"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--          <a-->
        <!--            v-if="!formData.planCode"-->
        <!--            class="clickChoose_button"-->
        <!--            @click.prevent="choosePeople"-->
        <!--          >-->
        <!--            <svg-icon icon-class="选择弹框" />-->
        <!--          </a>-->
        <!--        </el-form-item>-->
        <el-form-item label="计划单号" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.productionPlanCode" disabled />
          <!--          <a-->
          <!--            class="clickChoose_button"-->
          <!--            @click.prevent="chooseMaterial"-->
          <!--          >-->
          <!--            <svg-icon icon-class="选择弹框" />-->
          <!--          </a>-->
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        物料明细
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a v-if="!this.$store.state.order.isPurchase && !this.isSelectPurchase" class="formItem_header_operate_item" @click="importSpareParts">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a>
          <a v-else class="formItem_header_operate_itemOne">
            <svg-icon icon-class="导入" />
            <span class="el-button--text button_grey">导入</span>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="detailDate"
          max-height="400"
          stripe
          border
          style="width: 99.9%"
          :summary-method="getSummaries"
          :header-cell-class-name="headerCellClassName"
          show-summary
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" width="80" />
          <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" :min-width="SETTINGS.settings_decimalDigits_length">
            <template slot-scope="scope">
              <span>{{ scope.row.stockNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="需求数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="requireNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.requireNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="申请数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="applicationNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.applicationNumber" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="已申请数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="appliedNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.appliedNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="在途数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="transitNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.transitNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="需求日期" min-width="140">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.requireTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :editable="false"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="附件"
            min-width="140"
          >
            <template slot-scope="scope">
              <FileManage
                v-if="!scope.row.isAdd"
                :file-names.sync="scope.row.fileName"
                :file-real-names.sync="scope.row.fileRealName"
                :file-urls.sync="scope.row.fileUrl"
                :row-index="scope.$index"
                @fileName="setFileName"
              />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <div>
        <span v-if="showSchedule" style="color:#999999">明细导入中...({{ progressTitle }}%)</span>
        <span v-if="showSuccess" style="color:#19BE6B">导入成功</span>
        <span v-if="showFail" style="color:#e76c6c">导入失败</span>
      </div>
      <div>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
        <el-button @click.stop="onSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, planPassageNum, importPurchaseApply } from '@/api/purchaseManage/purchaseApply'
import searchMaterial from '../../warehouseManagement/materialInfo/addMaterialInfo.vue'
import moment from 'moment'
import ImportData from '@/components/JLink/common/ImportData'
import addSupplies from './addSupplies'
import Big from 'big.js'
import { getInfoByConfigKey } from '@/api/outsourceManage/outsourceReturnMaterial' // big.js解决精度丢失问题
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    resData: {}
  },
  data() {
    return {
      progressTitle: '0',
      showSchedule: false,
      showSuccess: false,
      showFail: false,
      timer: undefined,
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        simpleName: undefined,
        categoryCode: undefined,
        belongBysStr: undefined,
        typeId: undefined,
        model: undefined,
        purchaseTime: undefined,
        userId: undefined,
        protoId: undefined,
        protoName: undefined,
        typeName: undefined,
        realName: undefined,
        purchaseTypeCode: '',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        applicationTime: '',
        remark: undefined,
        status: 0,
        detailList: []
      },
      cloneData: [],
      isSelectPurchase: '',
      tableHeight: '',
      selectionsAll1: [],
      pageId: '采购申请单物料明细', // 页面唯一标识
      planIdData: [],
      ids: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      detailDate: [],
      rules: {
        purchaseTypeCode: [
          { required: true, message: '采购类型不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '申请单号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
  },
  created() {
    if (!this.id) { // 没有id就是新增
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  beforeDestroy() {
    this.$store.state.order.purchaseData = []
    this.$store.state.order.isPurchase = false
    this.$store.state.order.requestId = ''
  },
  mounted() {
    console.log('this.resData', this.resData)
    if (this.resData) {
      this.detailDate = this.resData
      this.planIdData = this.resData
      this.planIdData.forEach(item2 => {
        item2.productionPlanId = this.$store.state.order.requestId
        this.formData.productionPlanId = this.$store.state.order.requestId
        this.formData.productionPlanCode = item2.materialCodeOne
        item2.id = ''
        item2.remark = ''
        delete item2.id
      })
      this.getPlanPassageNum()
    }
    this.formData.applicationName = this.$store.state.user.name
    this.formData.applicationBy = this.$store.state.user.userId
    this.formData.applicationTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {

    headerCellClassName(data) {
      if (['applicationNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    getPlanPassageNum() {
      const detailListOne = this.$deepClone(this.planIdData)
      planPassageNum(this.planIdData).then(res => {
        res.data.forEach((item, index) => {
          detailListOne.forEach(item2 => {
            if (item.materialId == item2.materialId) {
              item2.appliedNumber = item.appliedNumber
              item2.transitNumber = item.transitNumber
            }
          })
          if (res.data.length == index + 1) {
            this.detailDate = detailListOne
          }
        })
      })
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    // 合计行
    getSummaries(param) {
      const {
        columns,
        data
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        switch (column.property) {
          case 'requireNumber':
            sums[index] = data.map(item => item.requireNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
        switch (column.property) {
          case 'applicationNumber':
            sums[index] = data.map(item => item.applicationNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.applicationNumber = sums[index]
            break
        }
        switch (column.property) {
          case 'appliedNumber':
            sums[index] = data.map(item => item.appliedNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.appliedNumber = sums[index]
            break
        }
        switch (column.property) {
          case 'transitNumber':
            sums[index] = data.map(item => item.transitNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.transitNumber = sums[index]
            break
        }
      })
      return sums
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.detailDate = res.data.detailList
      })
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.detailDate.splice(this.detailDate.indexOf(item), 1)
      })
    },
    setFileName(...data) {
      console.log(data)
      this.cloneData = this.$deepClone(this.detailDate)
      // this.$set(this.detailDate[data[3]], 'fileName', data[0])
      // this.$set(this.detailDate[data[3]], 'fileRealName', data[1])
      // this.$set(this.detailDate[data[3]], 'fileUrl', data[2])
      // this.detailDate[data[3]].fileName = data[0]
      // this.detailDate[data[3]].fileRealName = data[1]
      // this.detailDate[data[3]].fileUrl = data[2]
      this.cloneData[data[3]].fileName = data[0]
      this.cloneData[data[3]].fileRealName = data[1]
      this.cloneData[data[3]].fileUrl = data[2]
      // console.log(this.detailDate)
      this.detailDate = this.$deepClone(this.cloneData)
      this.$refs.table.doLayout()
    },
    add() {
      const detailListTwo = this.$deepClone(this.detailDate)
      // detailListTwo.forEach(item => {
      //   this.isSelectPurchase = item.isSelectPurchase
      // })
      if (this.formData.productionPlanCode) {
        this.$layer.iframe({
          // 弹框
          content: {
            content: addSupplies, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              selectedRow: detailListTwo,
              requestId: this.formData.productionPlanId ? this.formData.productionPlanId : ''
            } // props
          },
          area: ['1320px', '700px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      } else {
        this.$layer.iframe({
          // 弹框
          content: {
            content: searchMaterial, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              selectedRow: this.detailDate
            } // props
          },
          area: ['1320px', '700px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      }
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.detailDate.length <= 0) {
            this.$message.warning('请添加物料明细')
            return
          }
          if (this.detailDate.filter(item => !item.applicationNumber).length > 0) {
            this.$message.warning('申请数量不能为空')
            return
          } else if (this.detailDate.some(item => item.applicationNumber && !this.SETTINGS.reg_no_zero.test(item.applicationNumber))) {
            this.$message.warning('申请数量未正确填写')
            return
          }
          this.formData.detailList = this.detailDate

          this.formData.applicationTime = this.formData.applicationTime ? this.formData.applicationTime : moment(new Date()).format('YYYY-MM-DD')
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    showMaterial(data) {
      console.log(data)
      data.forEach(item => {
        if (item.inventoryNumber == '' || item.inventoryNumber == null) {
          item.inventoryNumber = '0.00'
        }
        if (item.id == item.materialId) {
          item.id = ''
          item.remark = ''
          item.materialUnitLabel = item.materialUnitName
          delete item.id
        }
        if (!item.fileUrl) {
          item.fileName = ''
          item.fileRealName = ''
          item.fileUrl = ''
        }
      })
      this.cloneData = this.$deepClone(data)
      this.detailDate = data
      console.log(this.detailDate)
    },
    showMaterialOne(data) {
      data.forEach(item => {
        item.remark = ''
      })
      this.detailDate = data
      // this.formData.detailList.forEach(item => {
      //   item.remark = ''
      // })
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importPurchaseApply(files, (ps) => {
        this.showSchedule = true
        // this.progressTitle = Math.floor((ps.loaded / ps.total) * 100)
        this.progressTitle = 0
        this.timer = setInterval(() => {
          const num = Math.floor(Math.random() * 20) + 1
          if (this.progressTitle + num < 100) {
            this.progressTitle = this.progressTitle + num
          }
        }, 200)
        // }
      }).then(res => {
        setTimeout(() => {
          this.progressTitle = 100
          clearInterval(this.timer)
          if (res.data) {
            setTimeout(() => {
              this.showSchedule = false
              this.$nextTick(() => {
                this.showSuccess = true
                this.detailDate = []
                res.data.forEach(item => {
                  this.detailDate.push(item)
                })
                setTimeout(() => {
                  this.showSuccess = false
                }, 1000)
              })
            }, 500)
          }
        }, 2000)
        // this.progressTitle = 100
      }).catch(() => {
        this.progressTitle = 100
        clearInterval(this.timer)
        this.showSchedule = false
        this.$nextTick(() => {
          this.showFail = true
          setTimeout(() => {
            this.showFail = false
          }, 3000)
        })
      })
    }
    // importMethod(files) { // 导入接口
    //   importPurchaseApply(files, (ps) => {
    //     this.showSchedule = true
    //     this.progressTitle = Math.floor((ps.loaded / ps.total) * 100)
    //     if (this.progressTitle > 95) {
    //       this.progressTitle = 95
    //     }
    //   }).then(res => {
    //     this.progressTitle = 100
    //     if (res.data) {
    //       this.detailDate = []
    //       res.data.forEach(item => {
    //         this.detailDate.push(item)
    //       })
    //     }
    //   }).finally(() => {
    //     setTimeout(() => {
    //       this.showSchedule = false
    //     }, 200)
    //   })
    // }
    // importMethod(files) { // 导入接口
    //   importPurchaseApply(files).then(res => {
    //     if (res.data) {
    //       this.detailDate = []
    //       res.data.forEach(item => {
    //         // item.batchInventoryId = item.batchId
    //         this.detailDate.push(item)
    //       })
    //     }
    //   })
    // }
  }
}
</script>

<style lang="less" scoped>
.main_bottom{
  justify-content: space-between;
}
.table_container {
  padding-bottom: 20px !important;
}
/deep/ .el-table__fixed-footer-wrapper {
  .el-table__cell:last-of-type {
    height: 39px !important;
  }
}
.formItem_header_operate_itemOne {
  display: none;
}
</style>
